/**
 * @(#)JDOTuanGouItemStorage.java, 2010-5-13. 
 * 
 * Copyright 2010 Youdao, Inc. All rights reserved.
 * YOUDAO PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.rsstuan.storage.impl;

import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;

import com.rsstuan.storage.data.ArticleStorageData;
import com.rsstuan.storage.data.TuanGouItemData;

/**
 *
 * @author guosq
 *
 */
public class JDOTuanGouItemStorage {
    
    private static final Logger LOG = Logger.getLogger(JDOTuanGouItemStorage.class.getName());

    public void saveItem(TuanGouItemData item) {
        PersistenceManager pm = PMF.get().getPersistenceManager(); 
        try {
            pm.makePersistent(item);
        }
        finally {
            pm.close();
        }
    }
    
    public TuanGouItemData getItem(Long id) {
        PersistenceManager pm = PMF.get().getPersistenceManager(); 
        try {
            String query = "select from " + TuanGouItemData.class.getName()
                    + " where id ==" + id;
            List<TuanGouItemData> item = (List<TuanGouItemData>) pm.newQuery(query).execute();
            if (item != null && item.size() > 0)
                return item.get(0);
            return null;
        }
        finally {
            pm.close();
        }
        
    }
    
    public List<TuanGouItemData> getItems() {
        PersistenceManager pm = PMF.get().getPersistenceManager(); 
            try {
                String query = "select from " + TuanGouItemData.class.getName();
                List<TuanGouItemData> items = (List<TuanGouItemData>) pm.newQuery(query).execute();
                return items;
            }
            finally {
                //pm.close();
            }
        
    }
    
    public List<TuanGouItemData> getActivateItems() {
        PersistenceManager pm = PMF.get().getPersistenceManager(); 
        try {
            String query = "select from " + TuanGouItemData.class.getName()
                    + " where activate == true ";
            List<TuanGouItemData> items = (List<TuanGouItemData>) pm.newQuery(query).execute();
            return items;
        }
        finally {
           // pm.close();
        }
    }
    
    public List<TuanGouItemData> getActivateItemsByChannel(Long channelId) {
        PersistenceManager pm = PMF.get().getPersistenceManager(); 
        String query = "select from " + TuanGouItemData.class.getName()
                + " where activate == true && channelId == " + channelId;
        List<TuanGouItemData> items = (List<TuanGouItemData>) pm.newQuery(query).execute();
        
        return items;
    }
    
    public TuanGouItemData[] getActivateItemsBySite(Long siteId) {
        PersistenceManager pm = PMF.get().getPersistenceManager(); 
        String query = "select from " + TuanGouItemData.class.getName()
                + " where activate == true && siteId ==" + siteId
                + " order by storeTime";
        List<TuanGouItemData> items = (List<TuanGouItemData>) pm.newQuery(query).execute();
        if (items != null)
            return items.toArray(new TuanGouItemData[0]);
        return null;
    }
    
    public List<TuanGouItemData> getItemsByChannel(Long channelId) {
        PersistenceManager pm = PMF.get().getPersistenceManager();
        try {
            String query = "select from " + TuanGouItemData.class.getName()
                    + " where channelId ==" + channelId;
            // + " order by storeTime";
            List<TuanGouItemData> items = (List<TuanGouItemData>) pm.newQuery(
                    query).execute();
            return items;
        } finally {
           // pm.close();
        }
    }
    
    public List<TuanGouItemData> getItemsByTitle(Long channelId, String title) {
    	 PersistenceManager pm = PMF.get().getPersistenceManager();
         try {
             String query = "select from " + TuanGouItemData.class.getName()
                     + " where channelId ==" + channelId + " && title =='" + title + "'"; 
             // + " order by storeTime";
             List<TuanGouItemData> items = (List<TuanGouItemData>) pm.newQuery(
                     query).execute();
             return items;
         } finally {
            // pm.close();
         }
    }
    public boolean deactive(Long channelId) {
        PersistenceManager pm = PMF.get().getPersistenceManager(); 
        try {
            String query = "select from " + TuanGouItemData.class.getName() + " where activate == true";
            if (channelId != null) {
                    query += " && channelId ==" + channelId;
            }
            List<TuanGouItemData> items = (List<TuanGouItemData>) pm.newQuery(query).execute();
            for (TuanGouItemData item : items) {
                item.setActivate(false);
            }
            return true;
        }
        catch (Exception e) {
            LOG.log(Level.WARNING, "deactive fail", e);
            return false;
        }
        finally {
            pm.close();
        }
    }
    
    public boolean deactiveItem(Long itemId) {
        PersistenceManager pm = PMF.get().getPersistenceManager(); 
        try {
            String query = "select from " + TuanGouItemData.class.getName() + " where activate == true";
            if (itemId != null) {
                    query += " && id ==" + itemId;
            }
            List<TuanGouItemData> items = (List<TuanGouItemData>) pm.newQuery(query).execute();
            for (TuanGouItemData item : items) {
                item.setActivate(false);
            }
            return true;
        }
        catch (Exception e) {
            LOG.log(Level.WARNING, "deactive fail", e);
            return false;
        }
        finally {
            pm.close();
        }
    }


    public boolean activeItem(Long id) {
        PersistenceManager pm = PMF.get().getPersistenceManager(); 
        try {
            String query = "select from " + TuanGouItemData.class.getName() 
            + " where id ==" + id;
           
            List<TuanGouItemData> items = (List<TuanGouItemData>) pm.newQuery(query).execute();
            if (items != null) {
				for (TuanGouItemData item : items) {

					item.setActivate(true);
				}
			}
            return true;
        }
        catch (Exception e) {
            LOG.log(Level.WARNING, "active item=" + id + " fail", e);
            return false;
        }
        finally {
            pm.close();
        }
    }

    
	public boolean updateOrderNum(Long id, int orderNum) {
		 PersistenceManager pm = PMF.get().getPersistenceManager(); 
	        try {
	            String query = "select from " + TuanGouItemData.class.getName() 
	            + " where id == " + id;
	           
	            List<TuanGouItemData> items = (List<TuanGouItemData>) pm.newQuery(query).execute();
	            for (TuanGouItemData item : items) {
	                item.setOrderNum(orderNum);
	            }
	            return true;
	        }
	        catch (Exception e) {
	            LOG.log(Level.WARNING, "active item=" + id + " fail", e);
	            return false;
	        }
	        finally {
	            pm.close();
	        }
	  }
	
	public int addClick(Long id, int click) {
		 PersistenceManager pm = PMF.get().getPersistenceManager(); 
	        try {
	            String query = "select from " + TuanGouItemData.class.getName() 
	            + " where id == " + id;
	           
	            List<TuanGouItemData> items = (List<TuanGouItemData>) pm.newQuery(query).execute();
	            if (items != null && items.size() > 0) {
	            	TuanGouItemData item = items.get(0);
	            	int old = item.getClick();
	            	item.setClick(old + click);
	            	return (old + click);
	            }
	            return 0;
	            
	        }
	        catch (Exception e) {
	            LOG.log(Level.WARNING, "addClick " + id + " fail", e);
	            return -1;
	        }
	        finally {
	            pm.close();
	        }
	  }
	
	
	public TuanGouItemData[] getActiveItemsByCity(String city) {
		PersistenceManager pm = PMF.get().getPersistenceManager(); 
		try {
			String query = "select from " + TuanGouItemData.class.getName()
	                + " where activate == true && (city == '" + city + "' || city == '全国')" ;
	        List<TuanGouItemData> items = (List<TuanGouItemData>) pm.newQuery(query).execute();
	        if (items != null) {
	        	TuanGouItemData[] itemArray = new TuanGouItemData[items.size()];
	        	items.toArray(itemArray);
	        	return itemArray;
	        } else {
	        	return null;
	        }
	    }
		finally {
			pm.close();
		}
	}

    /**
     * @param id
     * @param score
     * @return
     */
    public double updateScore(Long id, Double score) {
        PersistenceManager pm = PMF.get().getPersistenceManager(); 
        try {
            String query = "select from " + TuanGouItemData.class.getName() 
            + " where id == " + id;
           
            List<TuanGouItemData> items = (List<TuanGouItemData>) pm.newQuery(query).execute();
            if (items != null && items.size() > 0) {
                TuanGouItemData item = items.get(0);
                double totalScore = item.getTotalScore() + score;
                int scorePeople = item.getScorePeople() + 1;
                item.setTotalScore(totalScore);
                item.setScorePeople(scorePeople);
                return (totalScore / scorePeople);
            }
            return 0;
            
        }
        catch (Exception e) {
            LOG.log(Level.WARNING, "updateScore " + id + " fail", e);
            return -1;
        }
        finally {
            pm.close();
        }
  }

	public boolean updateImageUrl(Long id, String image) {
		 PersistenceManager pm = PMF.get().getPersistenceManager(); 
	        try {
	            String query = "select from " + TuanGouItemData.class.getName() 
	            + " where id == " + id;
	           
	            List<TuanGouItemData> items = (List<TuanGouItemData>) pm.newQuery(query).execute();
	            for (TuanGouItemData item : items) {
	                item.setImage(image);
	            }
	            return true;
	        }
	        catch (Exception e) {
	            LOG.log(Level.WARNING, "active item=" + id + " fail", e);
	            return false;
	        }
	        finally {
	            pm.close();
	        }
	  }
}
